package com.ywu.standard.gateway.filter;

import com.ywu.standard.gateway.config.AppConfig;
import com.ywu.standard.gateway.handler.HandlerInterface;
import com.ywu.standard.gateway.handler.permission.impl.ApiRouterMssaHandlerInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @ClassName PermissionMssaHandlerFilter
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/9/28 9:43
 * @Version 1.0
 **/
@Component
@Slf4j
public class PermissionMssaHandlerFilter implements GlobalFilter, Ordered, HandlerInterface {
    @Autowired
    private List<ApiRouterMssaHandlerInterface> apiRouterPermissionList;

    @Autowired
    private AppConfig appConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 人机接口走PermissionHandlerFilter  机机接口走PermissionMssaHandlerFilter
        if (isOpenService(exchange)) {
            return chain.filter(exchange);
        }
        // 校验开关是否开启
        if (!appConfig.getCheckTokenAndPermission()) {
            return chain.filter(exchange);
        }
        log.info("PermissionMssaHandlerFilter start! apiRouterPermissionList size is {}", apiRouterPermissionList.size());
        // 判断是否需要拦截
        for (ApiRouterMssaHandlerInterface impl : apiRouterPermissionList) {
            Object handleRes = impl.handle(exchange);
            // 校验返回值是否为ServerWebExchange对象，如果不是，则构造返回体进行返回
            if (handleRes instanceof ServerWebExchange) {
                exchange = (ServerWebExchange) handleRes;
            } else {
                return generateResponseInfo(exchange, handleRes);
            }
        }
        log.info("PermissionMssaHandlerFilter end!");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 5;
    }
}
